import qs from 'qs';
import axios from 'axios';
const CFG = require('../config/dev.env');

global.APP = {
  fomdata (val) {
    let d = new Date(val)
    let year = d.getFullYear()
    let month = d.getMonth() + 1
    month = month < 10 ? '0' + month : month
    let day = d.getDate() < 10 ? '0' + d.getDate() : '' + d.getDate()
    let hour = d.getHours()
    let minutes = d.getMinutes()
    let seconds = d.getSeconds()
    let result = year + '-' + month + '-' + day + ' ' + hour + ':' + minutes + ':' + seconds
    return result
  },
  ajax: function (url, params, successCallback, errorCallback, useQs) {
    // 分解url判断请求方式，如果没有@默认为get请求
    let urlParams = url.split('@'),
      method = urlParams.length > 1 ? urlParams[0] : 'get',
      ajaxParams = method === 'get' ? { params: params } : params,
      ajaxUrl = urlParams.length > 1 ? urlParams[1] : url;

    ajaxUrl = ajaxUrl.indexOf('http') > -1 ? ajaxUrl : CFG.API_URL + ajaxUrl;

    let data = (useQs === false || method === 'get') ? ajaxParams : qs.stringify(ajaxParams);
    // axios 默认不发送cookie，跨域也是一个原因，需要全局设置
    // axios.defaults.withCredentials = 'true';

    axios[method](ajaxUrl, data).then(res => {
      // 如果返回404，则需要重新登录
      if (typeof res.data.status !== 'undefined' && res.data.status == 404) {
        let oauthUrl = 'http://m.lexikj.com/admin';
        window.location.href = oauthUrl;
        return
      }

      if (res.data.status === 403) {
        alert(res.data.msg)
        return
      }

      if (this.isCallback(successCallback)) {
        successCallback(res)
      }
    }).catch(err => {
      if (this.isCallback(errorCallback)) {
        errorCallback(err)
      }
    })
  },
  isCallback: function (callback) {
    return !(!callback || typeof callback === 'undefined' || callback === undefined)
  }
}